<template>
  <el-container class="m-el-container">
    <!-- 左侧边栏  -->
    <el-aside class="m-el-silde">
      <div class="button-tab">
        <!-- tab展开按钮 -->
        <el-icon @click="open = !open" size="24">
          <Fold v-if="open"></Fold>
          <Expand v-else></Expand>
        </el-icon>
      </div>
      <el-menu mode="vertical" class="main-menu" :router="true" :default-active="menu_option.active"
        @select="menuSelectHandle" :collapse="!open">
        <el-menu-item v-for="menuItem in tab_menu.options" :key="menuItem.id" :index="menuItem.id"
          :route="menuItem.path">
          <el-icon>
            <component :is="menuItem.icon"></component>
          </el-icon>
          <template #title>
            {{ menuItem.label }}
          </template>
        </el-menu-item>
      </el-menu>
    </el-aside>
    <!-- 右边 -->
    <el-main class="m-el-main" v-loading="exit_load">
      <!-- 头部 -->
      <el-header class="m-el-header" @click.stop="() => void 0">
        <el-row justify="space-between" align="middle" style="min-height: 50px">
          <el-col :span="4">
            <el-page-header v-if="is_index" :icon="ArrowLeft" @back="back_home"></el-page-header>
          </el-col>
          <el-col :span="1">
            <el-space>
              <el-dropdown v-if="user_data" @visible-change="(e) => (avg_hover = !e)" @command="user_click">
                <span :class="`button-avg ${avg_hover ? 'hover' : ''}`">
                  <el-image v-if="user_data.user_avg" :src="user_data.user_avg"></el-image>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item disabled style="cursor: auto; color: cadetblue">{{
                      user_data.name
                    }}</el-dropdown-item>
                    <el-dropdown-item command="user">个人资料</el-dropdown-item>
                    <el-dropdown-item command="set">设置</el-dropdown-item>
                    <el-dropdown-item command="exit" divided style="color: red">退出</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-button link v-else @click="userPanel" type="default" size="normal"> 登录 </el-button>
            </el-space>
          </el-col>
        </el-row>
      </el-header>
      <el-main class="main-body" v-loading="page.load">
        <!-- 视窗 -->
        <transition name="el-fade-in">
          <router-view></router-view>
        </transition>
      </el-main>
    </el-main>
  </el-container>
</template>

<script setup>

import { ref, reactive, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  str_utils,
  get as http_get,
  URL,
  post as http_post,
  user_info,
} from "@/tool/common";
import { tab_menu } from "@/tool/tab_config";
import { ElMessage, ElMessageBox } from "element-plus";
import {userInfoState} from "@/state/bus";
const open = ref(true);
const user_data = ref(null);
const router = useRouter();
const route = useRoute();
const page = reactive({
  load: false,
});
const exit_load = ref(false);
// menu active index
const menu_option = reactive({
  active: 0,
});


const is_index = computed(() => route.path.includes('detail'))
// 用户界面
function userPanel() {
  router.push({
    path: "/login",
  });
}
// 拼接数组
function toValue(arr, name, fill = ",") {
  if (!arr) {
    return;
  }
  let str = "";
  arr.forEach((i, b) => {
    str = str + i[name] + `${b === arr.length - 1 ? "" : fill}`;
  });
  return str;
}
// 拉取用户信息
function fetch_user_data() {
  user_info()
    .then((res) => {
      if (res && res.code && (res.code === 300 || res.code === 400)) {
        ElMessage.warning({
          message: "登录已过期",
          duration: 800,
        });
      } else if (res) {
        user_data.value = res["user_info"];
        
      }
    })
    .catch(() => {
      ElMessage.warning({
        message: "登录失效，请重新登录",
      });
    });
}
//用户菜单操作
function user_click(event) {
  if (str_utils.is_empty(event)) {
    return;
  }
  if (event === "exit") {
    exit_load.value = true;
    ElMessageBox.confirm(
      '确认退出当前账号吗？', '警告', {
      confirmButtonText: "确认",
      cancelButtonText: '点错了',
      s: 'warning',
      beforeClose(action, instance, done) {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true;
          http_get({
            url: URL.BASE + URL.API_USER_LOGOUT,
            params: {
              token: Cookies.get("token") || "",
            },
          }).then((res) => {
            if (res && (res.code === 200 || res.code === 400)) {
              Cookies.remove("token"); // 移除token
              done();
              window.location.reload();
              instance.confirmButtonLoading = false;
            }
          }).catch((err) => {
            console.error(err);
          });
        } else {
          done();
        }
      }
    })
  } else {
    router.push("/" + event);
  }
}
router.beforeEach((to, from) => {
  if (from.path === '/login' && (to.path === '/detail' || to.path === '/')) {
    
    fetch_user_data();
  }
});
function back_home() {
  router.back();
}

// 菜单点击
function menuSelectHandle(a, b) {
  return void (a);
}
</script>

<style lang="scss" scoped>
@import "@/common/style/common.scss";

.m-el-container {
  .tree-text {
    text-align: left;
    overflow: hidden;
    min-width: 120px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .full-content {
    width: 100%;

    .place-input {
      background-color: rgb(255, 255, 255);
      border-radius: 5px;
      box-sizing: border-box;
      height: 32px;
      width: fit-content;
    }
  }

  .my-divider {
    margin-top: 8px;
    margin-bottom: 8px;
  }

  height: 100%;

  .m-el-header {
    position: relative;
    z-index: 3;
    @include border();
    border-top-width: 0;
    border-left-width: 0;
    @include padding0(4px, 4px, 8px, 8px);
    height: auto;


  }

  .main-menu {
    margin-top: 24px;
    border: none;
    margin-right: 8px;
  }

  .m-el-main {
    overflow: hidden;
    position: relative;

    .main-body {
      height: 94%;
      @include padding0(6px, 0px, 6px, 6px);
    }

    @include padding0(0, 0, 0, 0);

    .template-tag {
      max-width: 98px;
      height: 32px;
      margin-right: 8px;
    }
  }

  .tag-container {
    @include border();
    min-width: 120px;
    max-height: 32px;
  }

  ::v-deep(.box-content) {
    display: none;
    justify-content: left;
    align-items: center;
  }

  .m-el-silde {
    overflow: hidden;
    box-sizing: content-box;
    position: relative;
    z-index: 2;
    width: auto;
    @include border(2px);
    border-top-width: 0;
    padding-right: 10px;

    .site-logo {
      margin-top: 10px;
      margin-left: 12px;
      margin-right: auto;
      width: 80px;
    }

    .button-tab {
      padding-top: 6px;
      position: relative;
      text-align: right;
      display: flex;
      justify-content: space-between;
      align-items: center;
      @include padding0(6px, 6px, 12px, 12px);

      i {
        cursor: pointer;
      }
    }
  }

  .button-avg {
    display: block;
    width: 50px;
    height: 50px;
    @include user_default_avg();
    outline: none;
    cursor: pointer;
    transition: transform 0.3s;
    overflow: hidden;
    border-radius: 25px;
    box-sizing: border-box;
    border: 2px solid transparent;

    .el-image {
      width: 100%;
      height: 100%;
    }
  }

  .hover {
    border-color: rergb(0, 183, 255);
    transform: translateY(5px) scale(1.16);
  }
}
</style>
